package com.woniuxy.aliyunoss.controller;

import com.aliyun.oss.OSSClient;
import com.woniuxy.commons.entity.UploadResult;
import com.woniuxy.commons.utils.ResStatus;
import com.woniuxy.commons.utils.ResponseResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @author Leimin
 * @date 2022/05/23 10:45
 **/
@RestController
@RequestMapping("/aliyunoss/file")
public class FileController {
    @Resource
    private OSSClient ossClient;
    //桶名
    private static final String BUCKET_NAME = "hospital-management-86";
    //服务器地址
    private static final String OSS_ADDRESS = "http://hospital-management-86.oss-cn-chengdu.aliyuncs.com/";

    @PostMapping("/upload")
    public ResponseResult<UploadResult> upload(MultipartFile file) throws IOException {
        //处理文件名，避免重复
        String fileName = file.getOriginalFilename();
        String fileExt = fileName.substring(fileName.lastIndexOf("."));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String date = sdf.format(new Date());
        String newName = date+"/"+UUID.randomUUID().toString().replace("-", "") + fileExt;
        //将文件上传到阿里云
        //1、获取文件输入流
        InputStream inputStream = file.getInputStream();
        //2、设置阿里云
        ossClient.putObject(BUCKET_NAME,newName,inputStream);
        //3、设置文件有效时间
        Date expireTime = new Date(System.currentTimeMillis() + 30 * 24 * 60 * 60 * 1000);
        //4、上传文件
        URL url = ossClient.generatePresignedUrl(BUCKET_NAME, newName, expireTime);
        //5、封装结果
        UploadResult result = new UploadResult(fileName, OSS_ADDRESS + newName);

        return new ResponseResult<>(200,"上传成功",result, ResStatus.SUCCESS);
    }

    @DeleteMapping("/del")
    public ResponseResult<Boolean> delete(String fileName){
        ossClient.deleteObject(BUCKET_NAME,fileName);
        return new ResponseResult<>(200,"删除成功",true,ResStatus.SUCCESS);
    }
}